package algorithm.leetcode;

public class Num142 {
    public static void main(String[] args) {
        ListNode head = new ListNode(3);
        ListNode head_1 = new ListNode(2);
        ListNode head_2 = new ListNode(0);
        ListNode head_3 = new ListNode(-4);
        head.next = head_1;
        head_1.next = head_2;
        head_2.next = head_3;
        head_3.next = head_1;
        System.out.println(detectCycle(head));
    }

    public static ListNode detectCycle(ListNode head) {
        if (head == null) return null;
        ListNode fast = head, slow = head;
        boolean loopExists = false;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                loopExists = true;
                break;
            }
        }
        if (loopExists) {
            slow = head;
            while (slow != fast) {
                slow = slow.next;
                fast = fast.next;
            }
            return slow;
        }
        return null;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    '}';
        }
    }
}
